package com.example.pixelyear.ui.act

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.pixelyear.Interface.OnBackUpClickListener
import com.example.pixelyear.Interface.OnOssBackUpListener
import com.example.pixelyear.Interface.OnOssRestoreListener
import com.example.pixelyear.Interface.OssType
import com.example.pixelyear.R
import com.example.pixelyear.ui.base.BaseActivity
import com.example.pixelyear.utils.*
import com.example.pixelyear.utils.dialog.BackupDialog
import com.example.pixelyear.utils.extension.setOnDoubleClickListener
import com.example.pixelyear.utils.extension.setVisi
import com.example.pixelyear.utils.oss.NetBackBackUpUtils
import com.socks.library.KLog
import kotlinx.android.synthetic.main.activity_setting.*
import kotlinx.android.synthetic.main.include_title.*
import org.json.JSONObject
import java.io.File
import java.io.FileInputStream
import java.io.InputStream

/**
 * 设置界面
 */
class SettingActivity : BaseActivity() {
    private val backup = 1
    private val restore = 2

    private val ossUtils by lazy {
        NetBackBackUpUtils.getInstance(mActivity)
    }

    private val backupDialog by lazy {
        BackupDialog(mActivity)
    }

    override fun setTitleBarColor() {
        UIUtils.setStatusBar(mActivity, 3, R.color.white)
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_setting
    }

    override fun initView(bundle: Bundle?) {
        yxstitle_TvTitle.text = "设置"
    }

    override fun initData() {

    }

    override fun initListener() {
        yxstitle_Imgback.setOnDoubleClickListener {
            YxsDisplay.finish(mActivity)
        }

        //编辑颜色
        Setting_EditColor.setOnDoubleClickListener {
            YxsDisplay.toEditColor(mActivity)
        }

        //备份
        Setting_BackUp.setOnDoubleClickListener {
            requestPermission(backup) {
                backupDialog.show(OssType.BackUp)
            }
        }

        //还原
        Setting_Restore.setOnDoubleClickListener {
            requestPermission(restore) {
                backupDialog.show(OssType.Restore)
            }
        }

        //教程
        Setting_Tutorial.setOnDoubleClickListener {
            YxsDisplay.toTutorial(mActivity)
        }

        //联系我
        Setting_CallMe.setOnDoubleClickListener {
            TipsDialogUtils.showSureCancelDialog(
                mActivity,
                content = "鄙人QQ：804036264\n\n使用上有什么问题或者有什么好想法都可以告诉我哦～",
                okText = "复制QQ号"
            ) {
                CopyUtils.copyString(mActivity, msg = "804036264")
                Utils.showToast("QQ已复制")
            }
        }

        //关于作者
        Setting_AboutAuthor.setOnDoubleClickListener {
            YxsDisplay.toAboutMe(mActivity)
        }

        //长按再次观看彩蛋
        Setting_AboutAuthor.setOnLongClickListener {
            val flag = YxsSpUtils.getBoolean(Constant.OPEN_SENIOR_EDIT_COLOR, false)
            if (flag)
                TipsDialogUtils.showOnlyTextDialog(mActivity, "再看一遍彩蛋") {
                    it.dismiss()
                    YxsDisplay.toAboutMe(mActivity, Bundle().apply {
                        putInt("random", 8)
                    })
                }
            return@setOnLongClickListener flag
        }

        //发电
        Setting_Power.setOnDoubleClickListener {
            YxsDisplay.toPower(mActivity)
        }

        Setting_Senior_Edit_Color.setOnCheckedChangeListener { _, isChecked ->
            KLog.e("yxs", "打开状态：$isChecked")
            YxsSpUtils.putBoolean(Constant.OPEN_SENIOR_COLOR, isChecked)
        }

        backupDialog.setListener(object : OnBackUpClickListener {

            override fun local(type: OssType) {
                loading.showD()

                if (type == OssType.BackUp) {
                    localBackUp()
                } else {
                    localRestore()
                }
            }

            override fun netWork(type: OssType) {
                if (type == OssType.BackUp) {
                    TipsDialogUtils.showEditDialog(mActivity, "提示") { pass, dialog ->
                        loading.showD()
                        netWorkBackUp(pass)
                        dialog.dismiss()
                    }
                } else {
                    if (checkFileExists())
                        netWorkRestore()
                    else showToast("未在远端找到你的备份！")
                }
            }

            override fun netWorkChangePhone(type: OssType) {
                TipsDialogUtils.showEditDialog(mActivity, "提示", hint = "请输入老手机的IMEI码") { imei, editDialog ->
                    if (checkFileExists(imei)) {
                        TipsDialogUtils.showEditDialog(mActivity, title = "提示", hint = "请输入密码") { pass, dialog ->
                            editDialog.dismiss()
                            loading.showD()
                            netWorkRestoreChangePhone(imei, pass)
                        }
                    } else showToast("未在远端找到你的备份！")
                }

            }
        })
    }

    override fun onResume() {
        super.onResume()
        Setting_Senior.setVisi(YxsSpUtils.getBoolean(Constant.OPEN_SENIOR_EDIT_COLOR, false))
        Setting_Senior_Edit_Color.isChecked =
            YxsSpUtils.getBoolean(Constant.OPEN_SENIOR_COLOR, true)
    }


    private fun netWorkBackUp(pass: String) {
        KLog.e("yxs", "网络备份密码：" + pass)
        val file = File(Environment.getDataDirectory().path + "/data/$packageName/databases/yxs.db")
        val localFileFolder = File(FunctionUtils.getDownloadAddressForAndroidVersion(mActivity))
        val dateFile = File(localFileFolder, "data")
        val json = JSONObject()
        json.put(
            "date", "${YxsSpUtils.getInt(
                Constant.FIRST_ENTER_APP_YEAR,
                Utils.getYear()
            )}-${YxsSpUtils.getInt(Constant.FIRST_ENTER_APP_MONTH, Utils.getMonth())}"
        )
        json.put(Constant.OPEN_SENIOR_EDIT_COLOR, YxsSpUtils.getBoolean(Constant.OPEN_SENIOR_EDIT_COLOR, false))
        json.put(Constant.OPEN_SENIOR_COLOR, YxsSpUtils.getBoolean(Constant.OPEN_SENIOR_COLOR, true))
        json.put(Constant.FILE_PASSWORD, pass)
        KLog.e("yxs", "百分生成文件：" + json.toString())
        Utils.writeText(
            json.toString()
            , dateFile
        )

        ossUtils.backUp("${FunctionUtils.getPhoneImei(mActivity)}backup", file.path, object : OnOssBackUpListener {
            override fun onSuccess() {
                KLog.e("yxs", "上传成功回调1：")
                ossUtils.backUp(
                    "${FunctionUtils.getPhoneImei(mActivity)}data",
                    dateFile.path,
                    object : OnOssBackUpListener {
                        override fun onSuccess() {
                            KLog.e("yxs", "上传成功回调2：")
                            showToast("备份成功！")
                            loading.dismiss()
                        }

                        override fun onFailure() {
                            showToast("出现了未知错误，请调整网络后重试！")
                            loading.dismiss()
                        }
                    })
            }

            override fun onFailure() {
                showToast("出现了未知错误，请调整网络后重试！")
                loading.dismiss()
            }
        })
    }

    private fun netWorkRestore() {
        ossUtils.restore("${FunctionUtils.getPhoneImei(mActivity)}backup", object : OnOssRestoreListener {
            override fun onSuccess(stream: InputStream) {

                ossUtils.restore("${FunctionUtils.getPhoneImei(mActivity)}data", object : OnOssRestoreListener {
                    override fun onSuccess(data: InputStream) {
                        val file = File(Environment.getDataDirectory().path + "/data/$packageName/databases/yxs.db")
                        Utils.copy(stream, file)
                        restoreDataFile(Utils.parsingInput(data))
                        loading.dismiss()
                    }

                    override fun onFailure() {
                        showToast("出现了未知错误，请调整网络后重试！")
                        loading.dismiss()
                    }
                })
            }

            override fun onFailure() {
                showToast("出现了未知错误，请调整网络后重试！")
                loading.dismiss()
            }
        })
    }

    //网络还原更换手机
    private fun netWorkRestoreChangePhone(imei: String, pass: String) {
        ossUtils.restore("${imei}data", object : OnOssRestoreListener {
            override fun onSuccess(data: InputStream) {
                val parsingInput = Utils.parsingInput(data)
                val json = JSONObject(parsingInput)
                KLog.e("yxs", "请求的数据文件：" + json)
                if (!json.isNull(Constant.FILE_PASSWORD)) {
                    if (pass == json.getString(Constant.FILE_PASSWORD)) {
                        ossUtils.restore("${imei}backup", object : OnOssRestoreListener {
                            override fun onSuccess(stream: InputStream) {
                                val file =
                                    File(Environment.getDataDirectory().path + "/data/$packageName/databases/yxs.db")
                                Utils.copy(stream, file)
                                loading.dismiss()
                                restoreDataFile(parsingInput)
                            }

                            override fun onFailure() {
                                showToast("出现了未知错误，请调整网络后重试！")
                                loading.dismiss()
                            }
                        })
                    } else {
                        showToast("密码错误！")
                        loading.dismiss()
                    }
                } else {
                    showToast("出现了未知错误，请调整网络后重试！")
                    loading.dismiss()
                }
            }

            override fun onFailure() {
                showToast("出现了未知错误，请调整网络后重试！")
                loading.dismiss()
            }
        })

    }


    private fun localBackUp() {
        KLog.e("yxs", "文件路径：${Environment.getDataDirectory().path}")
        val file = File(Environment.getDataDirectory().path + "/data/$packageName/databases/yxs.db")
        KLog.e("yxs", "文件是否存在：" + file.exists() + "===" + file.path)
        val localFileFolder = File(FunctionUtils.getDownloadAddressForAndroidVersion(mActivity))
        KLog.e("yxs", "本地文件夹地址：" + localFileFolder.path)
        if (!localFileFolder.exists())
            localFileFolder.mkdirs()
        val localFile = File(localFileFolder, "backup")
        if (!localFile.exists())
            localFile.createNewFile()
        Utils.copy(file.path, localFile.path)
        KLog.e("yxs", "备份成功：" + localFile.path)
        val dateFile = File(localFileFolder, "data")
        val json = JSONObject()
        json.put(
            "date", "${YxsSpUtils.getInt(
                Constant.FIRST_ENTER_APP_YEAR,
                Utils.getYear()
            )}-${YxsSpUtils.getInt(Constant.FIRST_ENTER_APP_MONTH, Utils.getMonth())}"
        )

        json.put(Constant.OPEN_SENIOR_EDIT_COLOR, YxsSpUtils.getBoolean(Constant.OPEN_SENIOR_EDIT_COLOR, false))
        json.put(Constant.OPEN_SENIOR_COLOR, YxsSpUtils.getBoolean(Constant.OPEN_SENIOR_COLOR, true))
        KLog.e("yxs", "百分生成文件：" + json.toString())
        Utils.writeText(
            json.toString()
            , dateFile
        )
        TipsDialogUtils.showSureCancelDialog(
            mActivity,
            cancelText = "",
            content = "备份成功，备份文件路径：\n${localFile.path}"
        ) {}
        loading.dismiss()

    }

    private fun localRestore() {
        val file = File(Environment.getDataDirectory().path + "/data/$packageName/databases/yxs.db")
        KLog.e("yxs", "数据库文件是否存在：" + file.exists())
        val localFileFolder =
            File(Environment.getExternalStorageDirectory().absolutePath + "/$packageName/backup")
        val dateFile =
            File(Environment.getExternalStorageDirectory().absolutePath + "/$packageName/data")
        if (!localFileFolder.exists()) {
            loading.dismiss()
            TipsDialogUtils.showSureCancelDialog(
                mActivity,
                okText = "生成文件夹",
                cancelText = "确定",
                content = "未找到备份文件，请在本地文件中新增${packageName}文件夹,并将backup文件和data文件放入文件夹中！"
            ) {
                val folder =
                    File(Environment.getExternalStorageDirectory().absolutePath + "/$packageName")
                KLog.e("yxs", "新建文件夹：" + folder.path + "===" + folder.exists())
                if (folder.exists())
                    Utils.showToast("文件夹已存在～")
                else {
                    val mkdirs = folder.mkdirs()
                    Utils.showToast("新建文件夹${packageName}${if (mkdirs) "成功" else "失败"}")
                }
            }
            return
        }
        val copy = Utils.copy(localFileFolder.path, file.path)
        if (copy) {
            KLog.e("yxs", "还原成功：" + localFileFolder.path)
            restoreDataFile(Utils.parsingInput(FileInputStream(dateFile)))
        } else Utils.showToast("还原失败！")
    }

    private fun restoreDataFile(json: String) {
        val parsingInput = JSONObject(json)
        KLog.e("yxs", "还原的首次登陆日期：${parsingInput.toString()}")
        if (!parsingInput.isNull(Constant.OPEN_SENIOR_EDIT_COLOR))
            YxsSpUtils.putBoolean(
                Constant.OPEN_SENIOR_EDIT_COLOR,
                parsingInput.getBoolean(Constant.OPEN_SENIOR_EDIT_COLOR)
            )
        if (!parsingInput.isNull(Constant.OPEN_SENIOR_COLOR))
            YxsSpUtils.putBoolean(Constant.OPEN_SENIOR_COLOR, parsingInput.getBoolean(Constant.OPEN_SENIOR_COLOR))
        if (!parsingInput.isNull("date"))
            with(parsingInput.getString("date").split("-")) {
                if (!isNullOrEmpty() && size == 2) {
                    YxsSpUtils.putInt(Constant.FIRST_ENTER_APP_YEAR, this[0].toInt())
                    YxsSpUtils.putInt(Constant.FIRST_ENTER_APP_MONTH, this[1].toInt())
                }
            }
        loading.dismiss()
        showToast("数据恢复成功，需要重新启动哦～")
        Utils.ReStartApp(mActivity, SplashActivity::class.java)
    }

    private fun requestPermission(code: Int, ret: () -> Unit) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_PHONE_STATE
            ) != PackageManager.PERMISSION_GRANTED)
        ) {
            ActivityCompat.requestPermissions(
                mActivity,
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE
                ),
                code
            )
        } else {
            ret.invoke()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        KLog.e("yxs", "请求权限返回：$requestCode ===${permissions.size} ===${grantResults.size}")
        if (grantResults.isNotEmpty()
            && grantResults[0] == PackageManager.PERMISSION_GRANTED
            && grantResults[2] == PackageManager.PERMISSION_GRANTED
        ) {
            if (requestCode == backup) {
                backupDialog.show(OssType.BackUp)
            } else {
                backupDialog.show(OssType.Restore)
            }
        } else {
            Utils.showToast("权限未授予，操作无法继续！")
        }
    }

    //在主线程弹出Toast
    fun showToast(msg: String) {
        runOnUiThread {
            Utils.showToast(msg)
        }
    }

    //检查文件在Oss服务器是否存在
    fun checkFileExists(imei: String = FunctionUtils.getPhoneImei(mActivity)): Boolean {
        KLog.e("yxs", "自己IMEI：$imei")
        return ossUtils.checkFileExists("${imei}data") && ossUtils.checkFileExists(
            "${imei}backup"
        )
    }

}
